<template>
  <div>
    <el-card>
      <el-input v-model="keyword" placeholder="请输入内容" style="width: 300px;height: 60px;margin-left: 30px" />
      <el-button type="primary" icon="el-icon-search" style="margin-left: 30px" @click="searchByKeyword">搜索</el-button>
      <el-button @click="emptyByKeyword">清空</el-button>
      <div>
        <el-button type="primary" icon="el-icon-plus" style="margin-left: 30px" @click="addUser('add')">添加</el-button>
        <el-button icon="el-icon-delete" type="danger" :disabled="flag" @click="deleteUsers">批量删除</el-button>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          label="序号"
          width="100"
          type="index"
        />
        <el-table-column
          prop="username"
          label="用户名"
          width="120"
        />
        <el-table-column
          prop="nickName"
          width="180"
          label="用户昵称"
        />
        <el-table-column
          prop="roleName"
          width="200"
          label="权限列表"
        />
        <el-table-column
          prop="gmtCreate"
          width="200"
          label="创建时间"
        />
        <el-table-column
          prop="gmtModified"
          label="更新时间"
        />
        <el-table-column
          prop="address"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="info" icon="el-icon-user" @click="isShowUser(scope)" />
            <el-button type="primary" icon="el-icon-edit" @click="addUser('edit',scope)" />
            <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scope)" />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="pageNo"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!--    角色授权对话框区域-->
    <el-dialog
      title="设置角色"
      :visible.sync="dialogVisible"
      width="50%"
      @closed="closeDialog"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.userId" disabled />
        </el-form-item>
        <el-form-item label="角色列表">
          <!--          设置 indeterminate 状态，只负责样式控制  false全选按钮不勾   ，，true全选按钮-这个样子-->
          <el-checkbox v-model="form.checkAll" :indeterminate="form.isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="form.checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(city,index) in form.cityOptions" :key="index" :label="city">{{ city }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserRole">确 定</el-button>
      </span>
    </el-dialog>
    <!--    添加或者编辑的对话框-->
    <el-dialog
      :title="title"
      :visible.sync="isShowdialogVisible"
      width="50%"
    >
      <el-form :model="addOrUpdateForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="addOrUpdateForm.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="addOrUpdateForm.nickName" />
        </el-form-item>
        <el-form-item v-show="isShowPassword" label="用户密码">
          <el-input v-model="addOrUpdateForm.password" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUesrTrue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  byUserRole,
  deleteUser,
  deleteUsersd,
  reqAddUser,
  reqEditUserNmae,
  reqRoleByUser,
  reqUserList
} from '@/api/user'

export default {
  name: 'User',
  data() {
    return {
      // input 双向绑定
      keyword: '',
      tableData: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      // 对话框区域
      dialogVisible: false,
      isShowdialogVisible: false,
      title: '',
      form: {
        userId: '',
        checkAll: false,
        cityOptions: [],
        checkedCities: [],
        checkedId: [],
        data: [],
        data1: [],
        isIndeterminate: true
      },
      addOrUpdateForm: {
        username: '',
        nickName: '',
        password: ''
      },
      isShowPassword: true,
      flag: true,
      reqList: []
    }
  },
  mounted() {
    this.getUserdata()
  },
  methods: {
    async getUserdata() {
      const { pageNo, pageSize } = this
      const res = await reqUserList(pageNo, pageSize, this.keyword)
      if (res.code === 20000) {
        this.tableData = res.data.items
        this.total = res.data.total
      }
    },
    // 点击搜索按钮的请求
    searchByKeyword() {
      this.getUserdata()
    },
    // 清空关键字
    emptyByKeyword() {
      this.keyword = ''
      this.getUserdata()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getUserdata()
    },
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo
      this.getUserdata()
    },
    // 点击按钮显示弹出层
    async  isShowUser(scope) {
      this.dialogVisible = true
      this.form.userId = scope.row.id
      const res = await reqRoleByUser(scope.row.id)
      if (res.code === 20000) {
        res.data.allRolesList.forEach((item) => {
          if (this.form.cityOptions.indexOf(item.roleName) === -1) {
            this.form.cityOptions.push(item.roleName)
          }
        })
        this.form.data = res.data.allRolesList
        this.form.data1 = res.data.assignRoles
        res.data.assignRoles.forEach((item) => {
          if (this.form.checkedCities.indexOf(item.roleName) === -1) {
            this.form.checkedCities.push(item.roleName)
          }
        })
        // this.form.checkAll = res.data.allRolesList.length === this.form.cityOptions.length
        // this.form.isIndeterminate = res.data.assignRoles.length > 0 && res.data.assignRoles.length < this.form.cityOptions.length
      }
    },
    handleCheckAllChange(val) {
      // 绑定全选按钮变化时发生的值，，val为true 或者fasle
      // this.userRoleIds = value ? this.allRoles.map(item => item.id) : []
      this.form.checkedCities = val ? this.form.cityOptions : []
      this.form.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      // 绑定多选框的值   value 是当前选中的数组
      this.form.checkedId = []
      console.log('绑定多选框的值', value, value.length)
      value.forEach((item) => {
        this.form.data.forEach((item1) => {
          if (item === item1.roleName) {
            if (this.form.checkedId.indexOf(item1.id) === -1) {
              this.form.checkedId.push(item1.id)
            }
          }
        })
      })

      const checkedCount = value.length
      this.form.checkAll = checkedCount === this.form.cityOptions.length
      this.form.isIndeterminate = checkedCount > 0 && checkedCount < this.form.cityOptions.length
    },
    // 关闭对话框
    closeDialog() {
      // 清空
      this.form.cityOptions = []
      this.form.checkedCities = []
    },
    async addUserRole() {
      const userId = this.form.userId
      if (this.form.checkedId.length < 1) {
        this.form.data1.forEach((item) => {
          this.form.checkedId.push(item.id)
        })
      }
      const roleId = this.form.checkedId.join(',')
      const res = await byUserRole(userId, roleId)
      if (res.code === 20000) {
        this.$message.success('更新成功')
        this.dialogVisible = false
      }
    },
    addUser(type, scope) {
      if (type === 'add') {
        this.isShowdialogVisible = true
        this.title = '添加用户'
      } else {
        this.isShowdialogVisible = true
        this.title = '编辑用户'
        this.addOrUpdateForm.username = scope.row.username
        this.addOrUpdateForm.nickName = scope.row.nickName
        this.addOrUpdateForm.id = scope.row.id
        this.isShowPassword = false
      }
    },
    async addUesrTrue() {
      if (this.addOrUpdateForm.password) {
        const reslut = await reqAddUser(this.addOrUpdateForm)
        console.log(reslut)
        if (reslut.code === 20000) {
          this.isShowdialogVisible = false
          this.$message.success('成功添加')
          this.addOrUpdateForm = {}
        } else {
          this.$message.error(reslut.message)
          this.addOrUpdateForm = {}
        }
      } else {
        this.addOrUpdateForm.password = undefined
        try {
          const res = await reqEditUserNmae(this.addOrUpdateForm)
          if (res.code === 20000) {
            this.$message.success('更新成功')
            this.isShowdialogVisible = false
            this.addOrUpdateForm = {}
          }
        } catch {
          this.isShowdialogVisible = false
          this.addOrUpdateForm = {}
        }
      }
    },

    // 删除某个用户
    async deleteUser(scope) {
      try {
        const res = await deleteUser(scope.row.id)
        console.log(res)
        if (res.code === 20000) {
          this.$message.success('删除成功')
          this.getUserdata()
        }
      } catch {
        console.log('系统数据，不能删除')
      }
    },
    handleSelectionChange(selection) {
      console.log(selection)
      this.reqList = selection.map((item) => {
        return item.id
      })
      this.flag = false
    },
    async deleteUsers() {
      const res = await deleteUsersd(this.reqList)
      if (res.code === 20000) {
        this.$message.success('批量删除成功')
        this.getUserdata()
      }
    }
  }

}
</script>

<style scoped>

</style>
